'use strict';

define([
  'angular',
  'angularAMD',
  'angular-cookies'
], function (ng, angularAMD) {

  /*字符串过长截取*/
  angularAMD.filter('cut', function () {
    return function (value, wordwise, max, tail) {
      if (!value) return '';
      max = parseInt(max, 10);
      if (!max) return value;
      if (value.length <= max) return value;

      value = value.substr(0, max);
      if (wordwise) {
        var lastspace = value.lastIndexOf(' ');
        if (lastspace != -1) {
          value = value.substr(0, lastspace);
        }
      }

      return value + (tail || ' …');
    };
  });
  /*字符串过长截取*/

  angularAMD.controller('categoriesCtrl', ['$scope', '$rootScope', '$http', '$cookies', '$location',
    function ($scope, $rootScope, $http, $cookies, $location) {

      var $w = $(window);
      $w.unbind("scroll");
      $cookies.remove('products_page', { path: '/' });
      $scope.selection = $location.search() || {};
      var myuser_id = $cookies.get('myuser_id');
      // console.log(myuser_id+'111');

      $scope.myuserId = myuser_id;

      $(".content-wrapper").css("min-height", 0);

      /*记忆选中的大分类*/
      var sc = window.sessionStorage;
      var fid = sc.getItem("currentFirst");
      var tid = sc.getItem("currentThird");
      var leftScroll = sc.getItem("leftScroll");
      var rightScroll = sc.getItem("rightScroll");
      if (fid) {
        $scope.selection.category_id = fid;
      }
      else {
        $scope.selection.category_id = 255;
      }
      /*记忆选中的大分类*/

      /*自适应分类高度*/
      resizeHeight();
      window.onresize = function () {
        resizeHeight();
      }
      /*自适应分类高度*/

      $scope.selectCategory = function (categoryId) {
        $scope.selection.category_id = categoryId;
        sc.setItem("currentFirst", categoryId);
        $('.right-layer').animate({ scrollTop: 0 }, 300);
      }

      $scope.gotoProducts = function (category_id) {
        $location.url('/products').search({ category: category_id });
        sc.setItem("currentThird", category_id);
        sc.setItem("leftScroll", $(".left-layer").scrollTop());
        sc.setItem("rightScroll", $(".right-layer").scrollTop());
      }

      //重设高度
      function resizeHeight() {
        var activeHeight = $w.height() - 108;
        $(".page-categories").css("height", activeHeight);
      }

      //根据某个字段排序
      function compare(property) {
        return function (a, b) {
          var value1 = a[property];
          var value2 = b[property];
          return value1 - value2;
        }
      }

      $http.get("index.php?route=feed/rest_api/categories&parent=0&level=3").then(
        function (result) {

          if (result.data.success) {
            $scope.categories = result.data.data;
            $scope.categories.sort(compare('class_sort'));
            var categoriesObj = {};
            if ($scope.categories && $scope.categories.length > 0) {
              angular.forEach($scope.categories, function (value, key) {
                if (!$scope.selection.category_id && key == 0) {
                  $scope.selection.category_id = value.category_id;
                }
                categoriesObj[value.category_id] = value;
              })
            }
            $scope._categories = categoriesObj;

            $('.left-layer').animate({ scrollTop: leftScroll }, 300);
            $('.right-layer').animate({ scrollTop: rightScroll }, 300);

          }

        }
      )

    }
  ]);

  angularAMD.controller('productsCtrl', ['$scope', '$http', '$location', '$cookies',
    function ($scope, $http, $location, $cookies) {

      /*商品列表高度session*/
      var sc = window.sessionStorage;
      var heightScroll = sc.getItem("heightScroll");
      /*商品列表高度session*/
      var myuser_id = $cookies.get('myuser_id');

      $scope.myuserId = myuser_id;
      // console.log(myuser_id);
      var searchObj = $location.search();
      var limit = 20, page = 1;
      var hasMore = true;
      var adding = false;
      $scope.searchParams = searchObj;
      searchObj.limit = limit;
      searchObj.page = page;
      $scope.need_scroll = false;

      var products_page = $cookies.get('products_page');
      if (products_page) {
        searchObj.page = products_page;
        page = products_page;
        var params = ng.copy($scope.searchParams);
        params.limit = products_page * limit;
        params.page = 1;
        loadProducts(params);
        $scope.need_scroll = true;
      } else {
        loadProducts(searchObj);
      }	  
	  
	  //跳转单品
      $scope.productInfo = function (id) {
        sc.setItem("heightScroll", $("body").scrollTop());
        $location.url('/product/' + id);
      }

      $scope.sort = function (key) {
        page = 1;
        $scope.searchParams.page = page;
        $scope.searchParams.sort = key;
        $scope.searchParams.order = $scope.searchParams.order && $scope.searchParams.order == "asc" ? "desc" : "asc";
        loadProducts($scope.searchParams);
      }

      if (searchObj.category) {
        $http.get("index.php?route=feed/rest_api/categories&id=" + searchObj.category).then(
          function (result) {
            if (result.data.success) {
              $scope.filterGroups = result.data.data.filters.filter_groups;
            }
          }
        )
      } else {
        $scope.filterGroups = [];
      }

      $scope.filter = function () {
        var filterIds = "";
        angular.forEach($scope.filterGroups, function (filterGroup, index) {
          if (filterGroup.currOption && filterGroup.currOption.filter_id) {
            filterIds += filterGroup.currOption.filter_id + ",";
          }
        })
        if (filterIds.charAt(filterIds.length - 1) == ",") {
          filterIds = filterIds.substring(0, filterIds.length - 1);
        }
        page = 1;
        var searchParams = { category: searchObj.category, page: page, limit: limit };
        if (filterIds && filterIds.length > 0) {
          searchParams.filter = filterIds;
          $scope.filterIds = filterIds;
          $scope.filtering = true;
        } else {
          $scope.filtering = false;
        }
        loadProducts(searchParams);
        $scope.showFilterPanelFlag = false;
      }

      $scope.showFilterPanel = function () {
        if (!searchObj.category) {
          BHZ.MessageBox.show("没有商品分类ID,不能筛选！");
          return;
        }
        $scope.showFilterPanelFlag = true;
      }

      $scope.closeFilterPanel = function () {
        $scope.showFilterPanelFlag = false;
      }

      $scope.selectOption = function (filterGroup, filterOption) {
        if (filterGroup.currOption && filterGroup.currOption.filter_id == filterOption.filter_id) {
          filterGroup.currOption = {};
        } else {
          filterGroup.currOption = filterOption;
        }
      }

      $scope.addToCart = function (product) {
        if (adding) {
          return;
        }
        var option = {};
        if (product.options.length > 1) {

          BHZ.MessageBox.show("此商品需在进入商品详情页面后再选择下单。");
          return;

        } else if (product.options.length == 1) {
          if (!product.options[0].flag) {

            BHZ.MessageBox.show("此商品需在进入商品详情页面后再填写下单。");
            return;

          } else if (product.options[0].option_value.length > 1) {

            BHZ.MessageBox.show("此商品需在进入商品详情页面后再选择下单。");
            return;

          }
        }

        if (product.options && product.options.length > 0) {
          option[product.options[0].product_option_id] = product.options[0].option_value[0].product_option_value_id;
        }

        var params = {
          "product_id": product.id,
          "show_cart": product.show_cart,
          "quantity": product.minimum,
          "option": option
        }
        adding = true;
        $http.post("index.php?route=rest/cart/cart", params).then(
          function (result) {
            console.log(result);
            adding = false;
            if (result.data.success) {
              BHZ.MessageBox.show("加入进货单成功!");
            }
            else {
              BHZ.MessageBox.show("加入进货单失败");
            }
          }, function (error) {
            adding = false;
          }
        )
      }

      var $w = $(window);
      $(".content-wrapper").css("min-height", $w.height());
      $(".filter-panel").css("min-height", $w.height());

      $w.unbind("scroll");
      $w.bind("scroll", function () {
        if ($("#LoadingPlace").length > 0 && $w.scrollTop() + $w.height() > $("#LoadingPlace").offset().top && hasMore) {
          var params = ng.copy($scope.searchParams);
          if ($scope.filterIds) {
            params.filter = $scope.filterIds;
          }
          if (page == 1) {
            page = 2;
          }
          params.page = page;
          $cookies.put('products_page', page, { path: '/' });
          loadMoreProducts(params);
        }

        if ($("#LoadingPlace").length > 0) {
          if ($w.scrollTop() > 100) {
            $cookies.put('scroll_position', $w.scrollTop(), { path: '/' });
          }
        }

      });

      function loadMoreProducts(searchParams) {
        if ($scope.loading) {
          return;
        }
        var baseUrl = "index.php?route=feed/rest_api/products&simple=1";
        for (var key in searchParams) {
          if (searchParams[key]) {
            baseUrl += "&" + key + "=" + searchParams[key];
          }
        }
        $scope.loading = true;
        $http.get(baseUrl).then(
          function (result) {
            $scope.loading = false;
            page++;
            if (result.data.success) {
              if (result.data.data.length == 0) {
                hasMore = false;
                $scope.withoutMore = true;
                return;
              }
              // console.log($scope.products);
              if ($scope.products && $scope.products.length > 0) {
                angular.forEach(result.data.data, function (productItem) {
                  $scope.products.push(productItem);
                })
              } else {
                $scope.products = result.data.data;
                if ($scope.products.length == 0 || $scope.products.length < limit) {
                  $scope.withoutMore = true;
                }
              }
            } else {
              $scope.products = [];
              $scope.withoutMore = true;
            }
          }, function (error) {
            $scope.loading = false;
          }
        )
      }

      function loadProducts(searchParams) {
        if ($scope.loading) {
          return;
        }
        var baseUrl = "index.php?route=feed/rest_api/products&simple=1";
        for (var key in searchParams) {
          if (searchParams[key]) {
            baseUrl += "&" + key + "=" + searchParams[key];
          }
        }
        $scope.loading = true;
        $http.get(baseUrl).then(
          function (result) {
            $scope.loading = false;
            if (result.data.success) {
              $scope.products = result.data.data;

              if (result.data.correct) {
                var a = result.data.correct;
                var b = result.data.expand;
                $scope.helps = $.unique(a.concat(b).sort());
              }

            } else {
              $scope.products = [];
            }
            if ($scope.products.length == 0 || $scope.products.length < limit) {
              $scope.withoutMore = true;
            }
            if ($scope.need_scroll) {
              setTimeout(function () {
                var scroll_position = $cookies.get('scroll_position');
                //$('body').scrollTop(scroll_position);  

				//返回商品列表高度
				$("body").animate({ scrollTop: heightScroll });
				sc.setItem("heightScroll", 0); //重置session高度0

              }, 500);

              $scope.need_scroll = false;
            }

          }, function (error) {
            $scope.loading = false;
          }
        )
      }
    }
  ]);

  angularAMD.controller('productCtrl', ['$routeParams', '$cookies', '$scope', '$sce', '$http', '$location', '$timeout', '$window', 'BHZConfig',
    function ($routeParams, $cookies,$scope, $sce, $http, $location, $timeout, $window, BHZConfig) {
      var $w = $(window);
      $w.unbind("scroll");
      var myuser_id = $cookies.get('myuser_id');
      // console.log(myuser_id+'111');

      $scope.myuserId = myuser_id;

      var productImagesSlider, initSwiperFlag;
      var productId = $routeParams.product_id;
      var adding = false;
      if (!productId) {
        alert("缺少商品ID!");
        return;
      }
      $scope.BHZConfig = BHZConfig;

      //将本页从头开始
      $window.scrollTo(0, 0)

      $scope.selection = {
        tab: 1,
        secondTab: 1,
        quantity: 1
      }

      $http.get("index.php?route=feed/rest_api/products&id=" + productId).then(
        function (result) {
          if (result.data.success) {
            var product = result.data.data;
            product.description = $sce.trustAsHtml(product.description);
            var attrArgs = [];
            if (product.attribute_groups && product.attribute_groups.length > 0) {
              angular.forEach(product.attribute_groups, function (attr_group, index) {
                if (attr_group.attribute) {
                  angular.forEach(attr_group.attribute, function (attr_item, index) {
                    attrArgs.push(attr_item);
                  })
                }
              })
              product.attr_args = attrArgs;
            }
            if (product.images) {
              product.images.splice(0, 0, product.image);
            }
            if (product.reviews && product.reviews.reviews) {
              angular.forEach(product.reviews.reviews, function (review) {
                if (review.author.length > 2) {
                  review.author = review.author.charAt(0) + "***" + review.author.charAt(review.author.length - 1);
                }
                review.avatar = review.avatar || "catalog/view/theme/bhz/m/images/default-avarta.png";
              })
            }
            $scope.product = product;
            $scope.selection.quantity = $scope.product.minimum;
            if (product.options.length > 0) {
              $scope.product_option_id = product.options[0].product_option_id;
              if ($scope.product.options[0].option_value) {
                $scope.switchOption(0);
                $scope.selection.quantity = $scope.product.minimum;
              }
            }
          }
        }
      )

      $scope.addTowishlist = function () {
        if ($scope.product.is_in_wishlist) {
          $http.delete('index.php?route=rest/wishlist/wishlist&id=' + productId).then(function (result) {
            if (result.data.success) {
              $scope.product.is_in_wishlist = false;
              BHZ.MessageBox.show("取消关注成功！");
            }
          })
        } else {
          $http.post('index.php?route=rest/wishlist/wishlist&id=' + productId).then(function (result) {
            if (result.data.success) {
              $scope.product.is_in_wishlist = true;
              BHZ.MessageBox.show("加入收藏成功");
            }
          })
        }
      }

      $scope.addToCart = function (inSelectOptionPanel) {
        if (($scope.product.options && $scope.product.options.length > 0) && (!$scope.currProductOption || !$scope.currProductOption.product_option_value_id)) {
          if (inSelectOptionPanel) {
            BHZ.MessageDialog.show("请选择规格尺寸", "知道了");
          } else {
            $scope.selectOption();
          }
          return;
        }
        if (parseInt($scope.selection.quantity) < parseInt($scope.product.minimum)) {
          if (inSelectOptionPanel) {
            alert("商品购买数量不能小于起批个数！");
          } else {
            BHZ.MessageDialog.show("商品购买数量不能小于起批个数！", "知道了");
          }
          return;
        }

        if ($scope.product.is_single == 0) {
          BHZ.MessageDialog.show("B类商品不能单买");
        }
        if ($scope.product.show_cart == 2) {
          BHZ.MessageDialog.show("此商品正在备货中");
        }

        if (adding) {
          return;
        }
        var option = {};
        if ($scope.product.options && $scope.product.options.length > 0) {
          option[$scope.product_option_id] = $scope.currProductOption.product_option_value_id;
        }
        var params = {
          "product_id": productId,
          "show_cart": $scope.product.show_cart,
          "quantity": $scope.selection.quantity,
          "option": option
        }
        adding = true;
        if (inSelectOptionPanel) {
          $scope.closeSelectOption();
        }
        $http.post("index.php?route=rest/cart/cart", params).then(
          function (result) {
            adding = false;
            if (result.data.success) {
              BHZ.MessageBox.show("加入进货单成功！");
            } else {
              BHZ.MessageBox.show("加入进货单失败");
            }
          }, function (error) {
            adding = false;
          }
        )
      }

      /*组合商品快捷添加进货单*/
      $scope.fastAdd = function (data) {

        var id = data['id'];
        data['submitqty'] = $("input[name='submit-quantity" + id + "']").val();

        $scope.addSingleCart(1, data);

      }
      /*组合商品快捷添加进货单*/

      /*组合商品单独添加进货单*/
      $scope.addSingleCart = function (type, product) {
        var option = {};
        if (product.options && product.options.length > 0) {
          option[product.options[0].product_option_id] = product.options[0].product_option_value[0].product_option_value_id;
        }

        var params = {
          "product_id": product.id,
          "show_cart": product.show_cart,
          "quantity": product.submitqty,
          "option": option
        }

        $http.post("index.php?route=rest/cart/cart", params).then(
          function (result) {
            if (result.data.success) {
              if (type == 1) {
                BHZ.MessageBox.show("加入进货单成功！");
              }
            }
            else {
              BHZ.MessageBox.show("加入进货单失败");
            }
          }
        )

      }
      /*组合商品单独添加进货单*/

      /*组合商品批量添加进货单*/
      $scope.singleToCart = function () {

        var checkAll = true;
        var noChangeQty = true;
        var gproduct = [];
        $(".check-box").each(function () {

          if (this.checked == false) {
            checkAll = false;
          }
          else {

            if ($(this).parent().find("input[name='gp_is_single']").val() == 1) {

              var id = $(this).parent().find("input[name='gp_id']").val();
              var gps = $scope.product.group_products;

              for (var i = 0; i < gps.length; i++) {

                if (id == gps[i]['id']) {

                  gps[i]['submitqty'] = $("input[name='submit-quantity" + id + "']").val();

                  //判断数量是否和套装数量不同
                  if (gps[i]['submitqty'] != gps[i]['qty']) {
                    noChangeQty = false;
                  }

                  gproduct.push(gps[i]);

                }

              }

            }

          }

        });

        if (checkAll == true && noChangeQty == true) {

          $scope.addToCart();

        }
        else {

          if (gproduct.length == 0) {
            BHZ.MessageBox.show("请至少选择一件可单卖商品");
          }

          for (var i = 0; i < gproduct.length; i++) {

            $scope.addSingleCart(1, gproduct[i]);

          };

        }

      }
      /*组合商品批量添加进货单*/

      /*设置非单卖样式*/
      $scope.setStyle = function (args) {

        if (args != 1) {
          return 'cart-wrap single-wrap';
        }
        else {
          return 'cart-wrap';
        }

      }
      /*设置非单卖样式*/

      /*全选*/
      $scope.checkAll = function () {

        $(".check-box").each(function () {
          this.checked = true;
        });

      }
      /*全选*/

      /*清空*/
      $scope.cleanAll = function () {

        $(".check-box").each(function () {
          this.checked = false;
        });

      }
      /*清空*/

      /*批量购买*/
      $scope.batchBuy = function () {

        var checkAll = true;
        var noChangeQty = true;
        var gproduct = [];
        $(".check-box").each(function () {

          if (this.checked == false) {
            checkAll = false;
          }
          else {

            if ($(this).parent().find("input[name='gp_is_single']").val() == 1) {

              var id = $(this).parent().find("input[name='gp_id']").val();
              var gps = $scope.product.group_products;

              for (var i = 0; i < gps.length; i++) {

                if (id == gps[i]['id']) {

                  gps[i]['submitqty'] = $("input[name='submit-quantity" + id + "']").val();

                  //判断数量是否和套装数量不同
                  if (gps[i]['submitqty'] != gps[i]['qty']) {
                    noChangeQty = false;
                  }

                  gproduct.push(gps[i]);

                }

              }

            }

          }

        });

        if (checkAll == true && noChangeQty == true) {

          $scope.gotoBuy();

        }
        else {

          if (gproduct.length == 0) {
            BHZ.MessageBox.show("请至少选择一件可单卖商品");
          }

          for (var i = 0; i < gproduct.length; i++) {

            $scope.addSingleCart(2, gproduct[i]);

          };

          $location.url("/cart");

        }

      }
      /*批量购买*/

      $scope.gotoBuy = function (inSelectOptionPanel) {
        if (($scope.product.options && $scope.product.options.length > 0) && (!$scope.currProductOption || !$scope.currProductOption.product_option_value_id)) {

          if (inSelectOptionPanel) {
            alert("请选择规格尺寸");
          } else {
            BHZ.MessageDialog.show("请选择规格尺寸", "知道了");
          }
          return;
        }

        if ($scope.product.is_single == 0) {
          BHZ.MessageDialog.show("B类商品不能单买");
        }
        if ($scope.product.show_cart == 2) {
          BHZ.MessageDialog.show("此商品正在备货中");
        }

        if (parseInt($scope.selection.quantity) < parseInt($scope.product.minimum)) {
          if (inSelectOptionPanel) {
            alert("商品购买数量不能小于起批个数！");
          } else {
            BHZ.MessageDialog.show("商品购买数量不能小于起批个数！", "知道了");
          }
          return;
        }
        if (adding) {
          return;
        }
        var option = {};
        if ($scope.product.options && $scope.product.options.length > 0) {
          option[$scope.product_option_id] = $scope.currProductOption.product_option_value_id;
        }
        var params = {
          "product_id": productId,
          "show_cart": $scope.product.show_cart,
          "quantity": $scope.selection.quantity,
          "option": option
        }
        adding = true;
        $http.post("index.php?route=rest/cart/cart", params).then(
          function (result) {
            adding = false;
            if (result.data.success) {
              $location.url("/cart");
              $scope.closeSelectOption();
            } else {
              BHZ.MessageDialog.show("加入进货单失败，不能立即购买", "知道了");
            }
          }, function (error) {
            adding = false;
          }
        )
      }

      $scope.selectOption = function () {
        if ($(".cover").length == 0) {
          $("body").append("<div class='cover' style='display:none'></div>");
        }
        $(".cover").show();
        $scope.selectShow = true;
      }

      $scope.switchOption = function (key) {
        $scope.currProductOption = $scope.product.options[0].option_value[key];
        if ($scope.currProductOption.price_prefix == '+') {
          $scope.product.option_price = parseFloat($scope.product.special) + parseFloat($scope.currProductOption.price);
        } else {
          $scope.product.option_price = parseFloat($scope.product.special) - parseFloat($scope.currProductOption.price);
        }
        $scope.product.option_price = "￥" + $scope.product.option_price.toFixed(2);

      }

      $scope.closeSelectOption = function () {
        $scope.selectShow = false;
        $(".cover").hide();
      }

      $scope.updateQuantity = function (type) {
        if (!$scope.selection.quantity) {
          $scope.selection.quantity = 1;
        }
        if (type == "reduce") {
          if ($scope.selection.quantity > 1) {
            $scope.selection.quantity--;
          }
        } else if (type == "add") {
          $scope.selection.quantity++;
        }
      }

      $scope.initSwiper = function () {
        if (!initSwiperFlag) {
          initSwiperFlag = true;
          $timeout(function () {
            productImagesSlider = new Swiper('#productSlider', {
              loop: true,
              spaceBetween: 0,
              pagination: '#productSwiperPagination',
              paginationClickable: true,
              autoplay: 4000,
              paginationType: 'fraction'
            });
          })
        }
      }

      $scope.switchTab = function (tabIndex) {
        $scope.selection.tab = tabIndex;
      }

      $scope.back = function () {
        $window.history.back();
      }
    }
  ]);

  angularAMD.directive('onNgRepeatEnd', function ($timeout) {
    return {
      restrict: 'A',
      link: function ($scope, element, attr) {
        if ($scope.$last == true) {
          $timeout(function () {
            $scope.$eval(attr.onNgRepeatEnd);
          });
        }
      }
    };
  });

});